package com.ling.core.common.utils;

import com.bstek.dorado.data.Constants;
import com.bstek.dorado.data.provider.DataProvider;
import com.bstek.dorado.data.provider.manager.DataProviderManager;
import com.bstek.dorado.view.config.xml.ViewXmlConstants;
import com.bstek.dorado.view.manager.ViewConfig;
import com.bstek.dorado.view.manager.ViewConfigManager;
import com.bstek.dorado.view.service.DataServiceProcessorSupport.ParsedDataObjectName;
import com.bstek.dorado.web.DoradoContext;
import com.ling.pl.core.commons.utils.SpringUtil;

import javax.annotation.Resource;

/**
 * Dorado7 ViewManager工具类，利用该类可快速 取到ViewConfig、DataProvider之类Dorado7服务端对象
 *
 * @author bo.wang
 * @since 2013-1-30
 */

public class ViewManagerHelper {

    protected static final String PRIVATE_VIEW_OBJECT_PREFIX = ViewXmlConstants.PATH_VIEW_SHORT_NAME + Constants.PRIVATE_DATA_OBJECT_SUBFIX;
    @Resource
    private static ViewConfigManager viewConfigManager;
    @Resource
    private static DataProviderManager dataProviderManager;

    public static ViewConfig getViewConfig(DoradoContext context, String viewName)
            throws Exception {
        ViewConfig viewConfig = (ViewConfig) context.getAttribute(viewName);
        if (viewConfig == null) {
            viewConfig = getViewConfigManager().getViewConfig(viewName);
            context.setAttribute(viewName, viewConfig);
        }
        return viewConfig;
    }

    public static DataProvider getDataProvider(String dataProviderId)
            throws Exception {
        DataProvider dataProvider;
        // 判断是否View中的私有DataProvider
        if (dataProviderId.startsWith(PRIVATE_VIEW_OBJECT_PREFIX)) {
            ParsedDataObjectName parsedName = new ParsedDataObjectName(
                    dataProviderId);
            ViewConfig viewConfig = getViewConfig(DoradoContext.getCurrent(),
                    parsedName.getViewName());
            dataProvider = viewConfig.getDataProvider(parsedName
                    .getDataObject());
        } else {
            dataProvider = getDataProviderManager().getDataProvider(dataProviderId);
        }
        return dataProvider;
    }

    public static ViewConfigManager getViewConfigManager() {
        if (viewConfigManager == null) {
            viewConfigManager = SpringUtil.getBean(ViewConfigManager.class);
        }
        return viewConfigManager;
    }


    public static DataProviderManager getDataProviderManager() {
        if (dataProviderManager == null) {
            dataProviderManager = SpringUtil.getBean(DataProviderManager.class);
        }
        return dataProviderManager;
    }

}
